package com.jiyinit.web.core.mobile.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jiyinit.web.core.business.entity.TabCoreTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.TaskRequest;
import com.jiyinit.web.core.business.dto.UserTaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.service.TaskServiceImpl;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.DateUtil;
import com.jiyinit.web.core.common.util.UserUtil;

/**
 * 用户管理
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/muserTask")
public class MuserTaskController {
	/**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MuserTaskController.class);
    
    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskServiceImpl;
    @Resource(name = "core.taskServiceImpl")
    private TaskServiceImpl taskServiceImpl;
    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;
    
    
    /**
     * 按条件查询用户信息
     *
     * @param request
     * @return
     */
   
    @RequestMapping(method = RequestMethod.POST, value = "/findUserTasks")
    @ResponseBody
    public PagingResult<UserTaskVo> findByPage(HttpServletRequest request, UserTaskRequest userTaskRequest) {
    	userTaskRequest.setLimit(10);
        PagingResult<UserTaskVo> pagingResult = userTaskServiceImpl.findUserTasksByTaskId(userTaskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }
    
   
    
    
    /**
     * 新增任务
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/maddUserTask")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request) {
    	
    	UserTaskRequest userTaskRequest = getJsonToTaskRequest(request);
    	
        // 校验参数
        ValidateResult<UserTaskRequest> validateResult = paramCheckLogic.checkParamValidate(userTaskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
//        TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
//        BeanUtils.copyProperties(userTaskRequest, tabCoreUserTask);
        TabCoreTask task = new TabCoreTask();
        task.setTaskId(userTaskRequest.getTaskId());
        task.setEditTime(new Date());
        
        Integer[] userIdss = userTaskRequest.getAlloterIds();
        
	  	int num = 0;
	  	num = userTaskServiceImpl.addTaskAndUsers(userIdss,userTaskRequest.getTaskId(),userTaskRequest.getUserId(),task);
	     if (num > 0) {
	         return new ResponseEntity<>(ResponseDto.responseOK("success"), HttpStatus.OK);
	     }
	     return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
	        
	 }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 下午6:03:57
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updateUserTask")
    public ResponseEntity<ResponseDto> updateUserTask(HttpServletRequest request, UserTaskRequest userTaskRequest) {
        // 校验参数
    	Double plDays = 0.0;
        ValidateResult<UserTaskRequest> validateResult = paramCheckLogic.checkParamValidate(userTaskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        DateUtil std = new DateUtil();
        TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
        BeanUtils.copyProperties(userTaskRequest, tabCoreUserTask);
        
        Date startTimeReal = tabCoreUserTask.getStartTimeReal();
        Date endTimeReal = tabCoreUserTask.getEndTimeReal();
        double realDays = 0.0;
        if(startTimeReal !=null && endTimeReal !=null){
        	try {
        		realDays = (double)std.daysBetween(startTimeReal,endTimeReal);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
        	tabCoreUserTask.setRealDays(realDays+1);
        }
        tabCoreUserTask.setModifyTime(new Date());
        int num = userTaskServiceImpl.updateUserTask(tabCoreUserTask);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:49:23
         * @param 
         * @return
     */
    @RequestMapping("/userTaskLists")
    public String userTasks(HttpServletRequest request, Integer taskId) {
    	request.setAttribute("taskId", taskId);
    	request.setAttribute("alloterId", UserUtil.getCurrentUser().getUserId());
        return "/tasktouser/taskusers";
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月4日 上午9:01:17
         * @param 
         * @return
     */
    @RequestMapping("/update")
    public String update(HttpServletRequest request, Integer userTaskId) {
    	UserTaskVo userTaskVo = null;
    	userTaskVo = userTaskServiceImpl.findUserTaskById(userTaskId);
    	request.setAttribute("userTaskVo", userTaskVo);
        return "/tasktouser/taskAllotEdit";
    }

   
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月11日 上午11:00:10
         * @param 
         * @return
     */
    @RequestMapping("/fish")
    public ResponseEntity<ResponseDto> fish(HttpServletRequest request){
    	
    	UserTaskRequest userTaskRequest = getJsonToTaskRequest(request);
    	
    	List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
    	userTaskVos = userTaskServiceImpl.finAll(userTaskRequest);
    	if(userTaskVos.size()>0)
    		 return new ResponseEntity<>(ResponseDto.responseOK(userTaskVos), HttpStatus.OK);
    	return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);


    }
    
    /**
     * 按条件查询用户信息
     *
     * @param request
     * @return wuyuefeng
     */
   
    @RequestMapping(method = RequestMethod.POST, value = "/mfindUserTasks")
    @ResponseBody
    public ResponseEntity<ResponseDto> mfindUserTasks(HttpServletRequest request) {
    	UserTaskRequest userTaskRequest = getJsonToTaskRequest(request);
    	
    	List<UserTaskVo> UserTaskVos = new ArrayList<>();
    	UserTaskVos = userTaskServiceImpl.finAll(userTaskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{}", UserTaskVos.size());
        //if(UserTaskVos.size()>0)
   		 	return new ResponseEntity<>(ResponseDto.responseOK(UserTaskVos), HttpStatus.OK);
        //return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    
    private UserTaskRequest getJsonToTaskRequest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	UserTaskRequest userTaskRequest = (UserTaskRequest)JsonEntityTransform.json2Object(logJson, UserTaskRequest.class);
    	return userTaskRequest;
    }
   
    
   
    
}
